<template>
  <div class="container">
    <el-card>

      <template #header>
        <b>角色管理</b>
        <div class="table_tool">
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="showAddOrEdit = true"
            >新增</el-button
          >
        </div>
      </template>

      <el-table :data="tableData" border>
        <el-table-column prop="roleName" label="角色名称" />
        <el-table-column prop="description" label="角色描述" />
        <el-table-column label="操作" align="center">
          <template slot-scope="{ row }">
            <el-button type="text" @click="openEditDetail(row.id)"
              >编辑角色信息</el-button
            >
            <el-button type="text" @click="EditPermission(row.id)"
              >编辑权限</el-button
            >
            <!-- <el-button type="text" @click="openEditRow(row, 'builingForm', openAuthority)"
              >编辑权限</el-button
            > -->
            <el-button type="text" class="red" @click="delRoleById(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <footer class="footer">
      <el-pagination
        background
        layout="total, sizes, pager, jumper"
        :current-page="searchForm.page"
        :page-sizes="[20, 30, 50, 100]"
        :page-size="searchForm.page_size"
        :total="tableTotal"
        @size-change="changeSize"
        @current-change="changeCurrent"
      />
    </footer>

    <el-dialog
      class="auth_dialog"
      :title="builingForm.$id ? '编辑' : '新增'"
      :visible.sync="showAddOrEdit"
      width="666px"
      @closed="closeDialog()"
    >
      <el-form
        :model="builingForm"
        ref="builingForm"
        label-width="5em"
      >
        <el-form-item prop="$id" hidden />
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="builingForm.name"
            placeholder="请输入角色名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="builingForm.description"
            placeholder="请输入角色描述"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button
          type="primary"
          @click="submit()"
          :loading="loading.update"
          >确 定</el-button
        >
      </template>
    </el-dialog>

    <el-dialog
      class="auth_dialog"
      :title="authForm.$id ? '编辑' : '新增'"
      :visible.sync="showPermission"
      width="666px"
      @closed="closePermissionDialog()"
    >
      <el-form
        :model="authForm"
        ref="authForm"
        label-width="5em"
      >
        <el-form-item prop="$id" hidden />
        <el-tree
          :data="authData"
          :props="defaultProps"
          ref="tree"
          show-checkbox
          node-key="id"
          default-expand-all
          @check-change="changeNode"
        >
        </el-tree>
      </el-form>
      <template #footer>
        <el-button
          type="primary"
          @click="submitPermission()"
          :loading="loading.update"
          >确 定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { table, addOrEdit } from "@/utils/mixins";
import {getStorage} from "@/utils/service/auth";
import API from '@/api';
import _ from "lodash";
export default {
  mixins: [table, addOrEdit],
  data: () => ({
    showAddOrEdit:false,
    showPermission:false,
    isLoading: true,
    tableData:[],
    tableTotal: 0,
    isKey: false,
    searchForm: {
      page: 1, // 当前页码
      per_page: 20, // 每页条数
    },
    builingForm: {
      $id:"",
      name: "",
      description:"",
      seq:"",
      icon_cls:"",
    },
    authData:[],
    authForm:{
      $id:'',
      resources:[]
    },
    auth:[],


    defaultProps: {
      children: "children",
      label: "label",
    },
  }),

  created() {
    this.loading=true
    this.isAdmin=getStorage("userInfo").wx_openid_id==1?true:false
    this.getPermissionList()
    API.getPermissionList({tree:1})
      .then(({data}) => {
        let authData = data.map((first) => {
          // 一级菜单
          let firstItem = {
            id: first.id,
            label: first.name,
            children: [],
          };
          if(first.children){
            first.children.map((two, tIdx) => {
              // 二级菜单
              firstItem.children.push({
                id: two.id,
                label: two.name,
              });
              if (two.children) {
                // 三级菜单
                firstItem.children[tIdx].children = two.children.map((three) => ({
                  id: three.id,
                  label: three.name,
                }));
              }
            });
          }
          return firstItem;
        });
        this.authData=authData;
      }).catch((err) => {
      }).finally(() =>{
        this.isLoading = false;
      })
  },

  methods: {
    changeSize(val){
      this.pagination.per_page = val
      this.getPermissionList()
    },

    changeCurrent(val){
      this.pagination.page = val
      this.getPermissionList()
    },

    // 获取角色·列表
    getPermissionList(){
      this.loading=true
      API.getRoleList(this.searchForm)
        .then(({data}) => {
          let roleList = data.map(item=>{
            return {
              id:item.id,
              roleName:item.name,
              description:item.description,
            }
          })

          this.tableData=roleList
          this.tableTotal=roleList.length
        }).catch((err) => {
        }).finally(() =>{
          this.isLoading = false;
        })
    },

    // 删除角色
    delRoleById(id){
      let _that=this
      if(_that.isAdmin){
        _that.$confirm(`是否删除改条数据？`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        })
        .then(() => {
          API.delRole(id)
          .then(({data}) => {
          }).catch((err) => {
          }).finally(() =>{
            _that.getPermissionList()
          })
        })
        .catch(() => {
        });
      }else{
        _that.$message.error("该账号暂无该权限！");
      }

   
    },

    // 新增角色
    submit(){
      let data={
        name:this.builingForm.name,
        description:this.builingForm.description,
        seq:"",
        icon_cls:"",
      }
      if(this.builingForm.$id){
        let id=this.builingForm.$id
        data.id=id
        API.editRole(id,data)
        .then(({data}) => {
          this.$message.success("编辑成功！");
        }).catch((err) => {
        }).finally(() =>{
          this.resetForm()
          this.getPermissionList()
        })
      }else{
        API.addRole(data)
        .then(({data}) => {
          this.$message.success("新增成功！");
        }).catch((err) => {
        }).finally(() =>{
          this.resetForm()
          this.getPermissionList()
        })
      }
    },

    // 编辑权限
    submitPermission(){
      let _that=this
        let id=_that.authForm.$id
        let resources= _that.authForm.resources
        API.editRolePermission(id,{resources:resources})
        .then(({data}) => {
          _that.$message.success("编辑成功！");
          _that.closePermissionDialog()
        }).catch((err) => {
        }).finally(() =>{
        })
    },

    // 打开弹窗（编辑）
    openEditDetail(id){
      let _that=this
        this.builingForm.$id=id
        API.getRoleDetail(id)
          .then(({data}) => {
            this.builingForm.$id=data.id
            this.builingForm.name=data.name
            this.builingForm.description=data.description
          }).catch((err) => {
          }).finally(() =>{
            this.showAddOrEdit=true
          })
    },

    // 编辑权限
    EditPermission(id){
      let _that=this
      _that.showPermission=true
      _that.authForm.$id=id
      API.getRolePermission(id)
      .then(({data}) => {
        _that.$refs.tree.setCheckedKeys(data);
      }).catch((err) => {
      }).finally(() =>{
      })
    },

    // 关闭弹窗
    closeDialog(){
      this.resetForm()
    },

    // 关闭权限弹窗
    closePermissionDialog(){
      this.$refs.tree.setCheckedKeys([]);
      this.showPermission=false
    },

    // 重置弹窗
    resetForm(){
      this.builingForm.$id=""
      this.builingForm.name=""
      this.builingForm.description=""
      this.showAddOrEdit=false
    },

    // 选择节点时
    changeNode(){
      let checkedKeys = this.$refs.tree.getCheckedKeys()
      this.authForm.resources = checkedKeys
    }
  },
};
</script>

<style lang="scss" scoped>
.role_tool {
  ::v-deep {
    .el-card__header {
      padding-bottom: 28px;
      align-items: center;
    }
  }
}
.auth_dialog {
  ::v-deep {
    .el-dialog__body {
      font-size: 16px;
      // padding-top: 0;
      max-height: 500px;
      overflow-y: scroll;
    }
    .el-dialog__footer {
      display: flex;
      justify-content: center;
    }
    // .el-tree-node {
    //   position: relative;
    //   z-index: 1;
    // }
    // .el-tree-node__content {
    //   display:inherit !important;
    //   .el-checkbox {
    //     position: absolute;
    //     right: 0;
    //   }
    // }
    .el-icon-user {
      color: #005dd6;
      font-weight: bolder;
      margin-right: 8px;
    }
  }
  .auth_title {
    height: 44px;
    padding-top: 4px;
    box-sizing: border-box;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .icon_file {
    width: 13px;
    height: 13px;
  }
}
</style>
